package com.snap.vseries.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.snap.vseries.R;
import com.snap.vseries.adapter.NewExpCycleStageAdapter;
import com.snap.vseries.adapter.NewExpLightingAdapter;
import com.snap.vseries.adapter.NewExpProgramAdapter;
import com.snap.vseries.base.BaseActivity;
import com.snap.vseries.base.OnItemClickListener;
import com.snap.vseries.bean.ExpEntity;
import com.snap.vseries.bean.ExpInfo;
import com.snap.vseries.bean.HoleInfo;
import com.snap.vseries.bean.ProgramRecycle;
import com.snap.vseries.bean.ProgramSection;
import com.snap.vseries.bean.ProgramStage;
import com.snap.vseries.manager.FileManager;
import com.snap.vseries.model.DBManager;
import com.snap.vseries.ui.widget.DialogView;
import com.snap.vseries.utils.ToastUtils;
import com.snap.vseries.utils.TopTitleUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 临时功能：本地添加模板。后期都会从远程获取
 * 添加/编辑 实验模板
 *
 * @author Rachel
 */
public class TemplateNewActivity extends BaseActivity implements CompoundButton.OnCheckedChangeListener {

    @BindView(R.id.fam_cb)
    CheckBox famCb;
    @BindView(R.id.vic_cb)
    CheckBox vicCb;
    @BindView(R.id.rox_cb)
    CheckBox roxCb;
    @BindView(R.id.cy5_cb)
    CheckBox cy5Cb;
    @BindView(R.id.device_rv)
    RecyclerView programRv;
    @BindView(R.id.analysis_rg)
    RadioGroup analysisRg;
    @BindView(R.id.cycle_stage_rv)
    RecyclerView cycleStageRv;
    @BindView(R.id.lighting_rv)
    RecyclerView lightingRv;
    @BindView(R.id.rg)
    RadioGroup rg;
    @BindView(R.id.template_name_tv)
    TextView templateNameTv;
    @BindView(R.id.fam_tv)
    TextView famTv;
    @BindView(R.id.vic_tv)
    TextView vicTv;
    @BindView(R.id.rox_tv)
    TextView roxTv;
    @BindView(R.id.cy5_tv)
    TextView cy5Tv;
    @BindView(R.id.recycle_stage_title_ll)
    LinearLayout recycleStageTitleLl;

    private ExpInfo templateInfo;
    private HoleInfo holeInfo;
    /**
     * 所有段信息
     */
    private List<ProgramStage> programStages;
    /**
     * 所有的节信息
     */
    private List<ProgramSection> sections;
    /**
     * 循环段
     */
    private ArrayList<ProgramRecycle> recycleStages;
    /**
     * 实验程序
     */
    private NewExpProgramAdapter programAdapter;
    /**
     * 设定循环，设定循环阶段，把节组装为段；
     * 数据源： List<ProgramRecycle> recycleStages
     * ProgramRecycle：段（包含段起始节，以及循环信息）
     */
    private NewExpCycleStageAdapter cycleAdapter;
    /**
     * 数据采集，是否采光
     * 每增加一个循环段，就增加相对应的段内节的采光开关
     */
    private NewExpLightingAdapter lightAdapter;


    @Override
    protected int layoutResId() {
        return R.layout.activity_template_new;
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initData();
        initViews();
    }

    private boolean isChooseTestingItem() {
        boolean isChooseTestingItem = false;
        for (int i = 0; i < rg.getChildCount(); i++) {
            if (((CheckBox) rg.getChildAt(i)).isChecked()) {
                isChooseTestingItem = true;
                break;
            }
        }
        return isChooseTestingItem;
    }

    @OnClick({R.id.template_name_tv, R.id.add_section_btn, R.id.add_recycle_stage_btn, R.id.btn_next, R.id.fam_tv, R.id.vic_tv, R.id.rox_tv, R.id.cy5_tv})
    public void click(View view) {
        switch (view.getId()) {
            case R.id.template_name_tv:
                rename();
                break;
            case R.id.add_section_btn:
                addSection();
                break;
            case R.id.add_recycle_stage_btn:
                //设定循环，添加段
                recycleStages.add(new ProgramRecycle(-1, -1, 40, false));
                updateCycleAdapter();
                break;
            case R.id.btn_next:
                if (templateInfo.getTestProject() == null || "".equals(templateInfo.getTestProject())) {
                    ToastUtils.get().showText("项目名称为必填选项");
                    return;
                }
                boolean hasRecyle = false;
                for (ProgramRecycle recycle : recycleStages) {
                    if (recycle.getStartIndex() != -1 && recycle.getEndIndex() != -1) {
                        hasRecyle = true;
                        break;
                    }
                }
                if (!hasRecyle) {
                    ToastUtils.get().showText("循环段不能为空");
                    return;
                }
                if (!isChooseTestingItem()) {
                    ToastUtils.get().showText("没有选择任何检测项目");
                    return;
                }
                makeProgram();
                addTemplate();
                break;
            case R.id.fam_tv:
                new DialogView(TemplateNewActivity.this).setTitle("请输入自定义通道名称")
                        .setTextLimit(10)
                        .setEditContent(templateInfo.getFamName() == null ? "" : templateInfo.getFamName())
                        .setOnClickListener(new DialogView.OnSureListener() {
                            @Override
                            public void onSureClick(String text) {
                                ((TextView) view).setText(text);
                                templateInfo.setFamName(text);
                            }
                        }).show();
                break;
            case R.id.vic_tv:
                new DialogView(TemplateNewActivity.this).setTitle("请输入自定义通道名称")
                        .setTextLimit(10)
                        .setEditContent(templateInfo.getVicName() == null ? "" : templateInfo.getVicName())
                        .setOnClickListener(new DialogView.OnSureListener() {
                            @Override
                            public void onSureClick(String text) {
                                ((TextView) view).setText(text);
                                templateInfo.setVicName(text);
                            }
                        }).show();
                break;
            case R.id.rox_tv:
                new DialogView(TemplateNewActivity.this).setTitle("请输入自定义通道名称")
                        .setTextLimit(10)
                        .setEditContent(templateInfo.getRoxName() == null ? "" : templateInfo.getRoxName())
                        .setOnClickListener(new DialogView.OnSureListener() {
                            @Override
                            public void onSureClick(String text) {
                                ((TextView) view).setText(text);
                                templateInfo.setRoxName(text);
                            }
                        }).show();
                break;
            case R.id.cy5_tv:
                new DialogView(TemplateNewActivity.this).setTitle("请输入自定义通道名称")
                        .setTextLimit(10)
                        .setEditContent(templateInfo.getCy5Name() == null ? "" : templateInfo.getCy5Name())
                        .setOnClickListener(new DialogView.OnSureListener() {
                            @Override
                            public void onSureClick(String text) {
                                ((TextView) view).setText(text);
                                templateInfo.setCy5Name(text);
                            }
                        }).show();
                break;
            default:
                break;
        }
    }

    private void initData() {
        sections = new ArrayList<>();
        recycleStages = new ArrayList<>();
        String name = getIntent().getStringExtra("name");
        ExpInfo project = FileManager.getInstance().getTempDataByName(name);
        if (project == null) {
            //初始化数据
            new TopTitleUtils(this).setTitle("新建检测项目");
            templateInfo = new ExpInfo();
            holeInfo = new HoleInfo();
            programStages = new ArrayList<>();
            templateInfo.setHoleInfo(holeInfo);

            sections.add(new ProgramSection(120, 50f, 1));
            sections.add(new ProgramSection(20, 95f, 2));
            sections.add(new ProgramSection(10, 95f, 3));
            sections.add(new ProgramSection(20, 55f, 4));
        } else {
            new TopTitleUtils(this).setTitle("编辑检测项目");
            templateInfo = project;
            holeInfo = templateInfo.getHoleInfo();
            programStages = templateInfo.getProgram();
        }
        for (ProgramStage stage : programStages) {
            sections.addAll(stage.getSections());
            if (stage.getCycleCount() > 1) {
                boolean lighting = false;
                int lightIndex = 0;
                for (int i = 0; i < stage.getSections().size(); i++) {
                    if (stage.getSections().get(i).isLighting()) {
                        lightIndex = stage.getSections().get(i).getSectionIndex();
                        lighting = true;
                        break;
                    }
                }
                addRecycleStage(new ProgramRecycle(stage.getSections().get(0).getSectionIndex(), stage.getSections().get(stage.getSections().size() - 1).getSectionIndex(), stage.getCycleCount(), lighting, lightIndex));
            }
        }
    }


    private void initViews() {
        templateNameTv.setText(templateInfo.getTestProject());
        //分析方法默认选中自动
        analysisRg.check(R.id.auto_rb);
        initChannel();
        programRv.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));

        programAdapter = new NewExpProgramAdapter(this, sections, getSupportFragmentManager());
        programRv.setAdapter(programAdapter);
        programAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView.Adapter adapter, View v, int position) {
                sections.remove(sections.get(position));
                for (int i = 0; i < sections.size(); i++) {
                    sections.get(i).setSectionIndex(i + 1);
                }
                // 只要执行删除节，就清空循环段
                programAdapter.updateData(sections);
                removeRecycleStage();

                updateCycleAdapter();
                lightAdapter.updateData(recycleStages);
            }
        });
        cycleAdapter = new NewExpCycleStageAdapter(this, recycleStages, sections.size());
        cycleStageRv.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        cycleStageRv.setAdapter(cycleAdapter);

        cycleAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView.Adapter adapter, View v, int position) {
                //循环段设置成功，更新采光列表
                lightAdapter.notifyDataSetChanged();
            }
        });
        cycleAdapter.setOnItemDeleteClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView.Adapter adapter, View v, int position) {
                updateCycleAdapter();
            }
        });

        lightAdapter = new NewExpLightingAdapter(this, recycleStages);
        lightingRv.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        lightingRv.setAdapter(lightAdapter);

    }

    private void updateCycleAdapter() {
        recycleStageTitleLl.setVisibility(recycleStages.size() == 0 ? View.GONE : View.VISIBLE);
        cycleAdapter.updateData(recycleStages, sections.size());
    }

    private void initChannel() {
        famCb.setChecked(holeInfo.isFamEnable());
        initFam(holeInfo.isFamEnable());
        vicCb.setChecked(holeInfo.isVicEnable());
        initVic(holeInfo.isVicEnable());
        roxCb.setChecked(holeInfo.isRoxEnable());
        initRox(holeInfo.isRoxEnable());
        cy5Cb.setChecked(holeInfo.isCy5Enable());
        initCy5(holeInfo.isCy5Enable());
        famCb.setOnCheckedChangeListener(this);
        vicCb.setOnCheckedChangeListener(this);
        roxCb.setOnCheckedChangeListener(this);
        cy5Cb.setOnCheckedChangeListener(this);
    }

    private void initCy5(boolean enable) {
        cy5Tv.setEnabled(enable);
        cy5Tv.setText(enable ? (templateInfo == null ? "" : templateInfo.getCy5Name()) : "请先启用通道");
    }

    private void initRox(boolean enable) {
        roxTv.setEnabled(enable);
        roxTv.setText(enable ? (templateInfo == null ? "" : templateInfo.getRoxName()) : "请先启用通道");
    }

    private void initVic(boolean enable) {
        vicTv.setEnabled(enable);
        vicTv.setText(enable ? (templateInfo == null ? "" : templateInfo.getVicName()) : "请先启用通道");
    }

    private void initFam(boolean enable) {
        famTv.setEnabled(enable);
        famTv.setText(enable ? (templateInfo == null ? "" : templateInfo.getFamName()) : "请先启用通道");
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()) {
            case R.id.fam_cb:
                holeInfo.setFamEnable(isChecked);
                initFam(isChecked);
                break;
            case R.id.vic_cb:
                holeInfo.setVicEnable(isChecked);
                initVic(isChecked);
                break;
            case R.id.rox_cb:
                holeInfo.setRoxEnable(isChecked);
                initRox(isChecked);
                break;
            case R.id.cy5_cb:
                holeInfo.setCy5Enable(isChecked);
                initCy5(isChecked);
                break;
            default:
                break;
        }
    }


    /**
     * sections->programStages的转化过程：节正序排列，根据recycleStages（循环段信息)构成段
     * sections:所有的节
     * programStages：所有的段，其中包括循环段和单次段
     * recycleStages:循环段信息
     */
    private void makeProgram() {
        programStages.clear();
        sortRecycleStages();
        //节序从1开始
        int startIndex = 1;
        for (ProgramRecycle recycle : recycleStages) {
            if (recycle.getStartIndex() == -1 || recycle.getEndIndex() == -1) {
                continue;
            }
            //将每个循环段前面的，不包含在循环段中的节（即循环次数为1的节），单独成段
            for (int i = startIndex; i < recycle.getStartIndex(); i++) {
                ProgramStage singleCycleStage = new ProgramStage();
                sections.get(i - 1).setCycleCount(1);
                sections.get(i - 1).setLighting(false);
                singleCycleStage.addSection(sections.get(i - 1));
                programStages.add(singleCycleStage);
            }
            //添加循环段（组装节）
            ProgramStage stage = new ProgramStage();
            List<ProgramSection> sectionList = new ArrayList<>();
            for (int j = recycle.getStartIndex(); j <= recycle.getEndIndex(); j++) {
                sections.get(j - 1).setLighting(recycle.isLighting() && recycle.getLightingIndex() == j);
                sections.get(j - 1).setCycleCount(recycle.getCycleCount());
                sectionList.add(sections.get(j - 1));
            }
            stage.setCycleCount(recycle.getCycleCount());
            stage.setSections(sectionList);
            programStages.add(stage);
            startIndex = recycle.getEndIndex() + 1;
        }
        //如果有循环数为1的节在后面，最后也要插入进去
        int endIndex = 0;
        if (recycleStages.size() > 0) {
            endIndex = recycleStages.get(recycleStages.size() - 1).getEndIndex();
        }

        if (endIndex < sections.size()) {
            for (int i = endIndex; i < sections.size(); i++) {
                ProgramStage singleCycleStage = new ProgramStage();
                sections.get(i).setLighting(false);
                singleCycleStage.addSection(sections.get(i));
                programStages.add(singleCycleStage);
            }
        }
        templateInfo.setProgram(programStages);
    }

    private void sortRecycleStages() {
        Collections.sort(recycleStages, (o1, o2) -> o1.getStartIndex() - o2.getStartIndex());
    }


    private void rename() {
        final DialogView dialogView = new DialogView(this);
        dialogView.setTitle("修改项目名称")
                .setEditContent(templateInfo.getTestProject() == null ? "" : templateInfo.getTestProject())
                .setClickSureDismissDialog(false)
                .setOnClickListener(content -> {
                    DBManager.get().getTemplateByName(content, entity -> {
                        if (entity == null) {
                            templateInfo.setTestProject(content);
                            dialogView.dismiss();
                            templateNameTv.setText(content);
                        } else {
                            ToastUtils.get().showText("项目已存在，请重新命名！");
                        }
                    });
                })
                .show();
    }

    /**
     * 点击添加一个节
     */
    private void addSection() {
        sections.add(new ProgramSection(10, 95f, sections.size() + 1));
        programAdapter.updateData(sections);
        updateCycleAdapter();
    }

    private void addTemplate() {
        boolean saveTemplate = FileManager.getInstance().saveTempData(templateInfo, templateInfo.getTestProject());
        if (saveTemplate) {
            ExpEntity templateEntity = new ExpEntity();
            templateEntity.setTestProject(templateInfo.getTestProject());
            templateEntity.setTemplate(true);
            templateEntity.setDescription("Additional brief description for this template's main application");
            boolean result = DBManager.get().saveTemplate(templateEntity);
            if (result) {
                ToastUtils.get().showText("保存模板成功");
                Intent intent = new Intent(this, HomeActivity.class);
                startActivity(intent);
            }
        }
    }

    private void addRecycleStage(ProgramRecycle programRecycle) {
        if (programRecycle != null) {
            recycleStages.add(programRecycle);
        }
    }

    private void removeRecycleStage() {
        recycleStages.clear();
        for (int i = 0; i < sections.size(); i++) {
            sections.get(i).setCycleCount(1);
        }
    }
}
